<template>
    <div>
        <!-- 搜索条 -->
        <div class="search">
            <div class="search-content">
                <div class="search-input">
                    <icon type="search" size='16'></icon>
                    <input type="text" @confirm="handleHistory"  @input="handleInput" placeholder="请输入关键字" v-model="keyword">
                </div>
                <button class="cancel" v-if="keyword" @click="cancelHandle">取消</button>
                <div class="search-modal" v-if="keyword">
                    <div class="search-item" v-for="item in resultList" :key="item.goods_id">{{item.goods_name}}</div>
                </div>
            </div>
        </div>
        <div class="history">
            <h4>搜索历史</h4>
            <icon @click="clearHandle" type='clear' size='16'/>
        </div>
        <div class="history-list">
            <div class="history-item" v-for="(item,index) in historyKey" :key="index">
                <navigator :url="'/pages/search_list/main?query='+item">
                {{item}}
                </navigator>
            </div>
        </div>
    </div>
</template>

<script>
import request from '../../utils/request.js'
export default {
    data() {
        return {
            keyword:'',
            resultList:[],
            timer:null,
            historyKey:wx.getStorageSync('history')||[]
        }
    },
    methods: {
        clearHandle() {
            wx.clearStorageSync()
            this.historyKey=[]
        },
        handleHistory() {
           this.historyKey.unshift(this.keyword)
           this.historyKey=[...new Set(this.historyKey)]
           wx.setStorageSync('history',this.historyKey)
           mpvue.navigateTo({
               url:"/pages/search_list/main?query="+this.keyword
           })
        },
        cancelHandle() {
           this.keyword=""
        },
        handleInput() {
            clearTimeout(this.timer)
            this.timer=setTimeout(async ()=>{
                 let res=await request('goods/qsearch',{query:this.keyword})
                 this.resultList=res.data.message
            },1000)
        }
    },
}
</script>

<style lang="less" scoped>
@import './main.less';
</style>
